//
//  KKWebViewController.m
//  FreightAssistant
//
//  Created by Mac mini on 15/12/11.
//  Copyright © 2015年 leo. All rights reserved.
//

#import "KKWebViewController.h"

#import <WebKit/WebKit.h>

@interface KKWebViewController () {
    
}

@end

@implementation KKWebViewController

- (void)loadView {
    [super loadView];
    
    UIView *rootView = [self view];
    _webView = [[KKWebView alloc] initWithFrame: rootView.bounds];
    [rootView addSubview: _webView];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear: animated];
    
    if (_requestURL) {
        [_webView kk_loadURLString: _requestURL];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Setter methods

- (void)setRequestURL:(NSString *)requestURL {
    
    _requestURL = requestURL;
    if (_webView) {
        [_webView kk_loadURLString: _requestURL];
    }
}

#pragma mark - Public methods

- (instancetype)initWithRequestURL:(NSString *)requestURL {
    
    self = [super init];
    if (self) {
        _requestURL = requestURL;
    }
    return self;
}

@end



#pragma mark -
#pragma mark - KKWebView methods

@interface KKWebView() <UIWebViewDelegate, WKNavigationDelegate> {
    
    UIWebView *_webView_7;
    WKWebView *_webView_8;
    BOOL _ios7_latter;
}

@end

@implementation KKWebView

- (void)awakeFromNib {
    
    [self initWithWebView];
}

- (instancetype)init {
    CGFloat webViewWidth = CGRectGetWidth([[UIScreen mainScreen] bounds]);
    CGFloat webViewHeight = CGRectGetHeight([[UIScreen mainScreen] bounds]);
    
    return [self initWithFrame: CGRectMake(0, 0, webViewWidth, webViewHeight)];
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame: frame];
    if (self) {
        
        [self initWithWebView];
    }
    return self;
}

#pragma mark - Private methods

- (void)initWithWebView {
    _ios7_latter = [[[UIDevice currentDevice] systemVersion] doubleValue] < 8.0 ? false : true;
    
    if (_ios7_latter) {
        
        _webView_8 = [[WKWebView alloc] initWithFrame: [self bounds]];
        _webView_8.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        _webView_8.navigationDelegate = self;
        [self addSubview: _webView_8];
    }
    else {
        _webView_7 = [[UIWebView alloc] initWithFrame: [self bounds]];
        _webView_7.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        _webView_7.delegate = self;
        [self addSubview: _webView_7];
    }
}

#pragma mark - Public methods

- (void)kk_loadURLString:(nonnull NSString *)urlString {
    
    if (urlString) {
        NSURLRequest *request = [NSURLRequest requestWithURL: [NSURL URLWithString: urlString]];
        [self kk_loadRequest: request];
    }
}

- (void)kk_loadRequest:(nonnull NSURLRequest *)request {
    
    if (_ios7_latter) {
        [_webView_8 loadRequest: request];
    }
    else {
        [_webView_7 loadRequest: request];
    }
}

- (void)kk_loadHTMLString:(nonnull NSString *)string baseURL:(nullable NSURL *)baseURL {
    
    if (_ios7_latter) {
        [_webView_8 loadHTMLString: string baseURL: baseURL];
    }
    else {
        [_webView_7 loadHTMLString: string baseURL: baseURL];
    }
}

- (void)kk_loadData:(nonnull NSData *)data MIMEType:(nonnull NSString *)MIMEType textEncodingName:(nonnull NSString *)textEncodingName baseURL:(nonnull NSURL *)baseURL {
    
    if (_ios7_latter) {
        [_webView_8 loadData: data MIMEType: MIMEType characterEncodingName: textEncodingName baseURL: baseURL];
    }
    else {
        [_webView_7 loadData: data MIMEType: MIMEType textEncodingName: textEncodingName baseURL: baseURL];
    }
}

- (nullable NSString *)stringByEvaluatingJavaScriptFromString:(nullable NSString *)script {
    if (_ios7_latter) {
        [_webView_8 evaluateJavaScript: script completionHandler:^(NSString *string, NSError * _Nullable error) {
//            return string;
        }];
    }
    else {
        return [_webView_7 stringByEvaluatingJavaScriptFromString: script];
    }
    
    return nil;
}

#pragma mark - UIWebViewDelegate methods

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
    if (_allowURLHost == nil) {
        return true;
    }
    else {
        NSString *host = request.URL.host.lowercaseString;
        if ([host isEqual: _allowURLHost]) {
            // 允许跳转
            return true;
        }
        // 不允许跳转
        return false;
    }
}


#pragma mark - WKNavigationDelegate methods

//  在收到响应后，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
    
    if (_allowURLHost == nil) {
        decisionHandler(WKNavigationResponsePolicyAllow);
        return;
    }
    else {
        
        NSString *host = navigationResponse.response.URL.host.lowercaseString;

        if ([host isEqual: _allowURLHost]) {
            // 允许跳转
            decisionHandler(WKNavigationResponsePolicyAllow);
            return;
        }
        // 不允许跳转
        decisionHandler(WKNavigationResponsePolicyCancel);
    }
}

//  在发送请求之前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    
    if (_allowURLHost == nil) {
        decisionHandler(WKNavigationActionPolicyAllow);
        return;
    }
    else {
        
        NSString *host = navigationAction.request.URL.host.lowercaseString;
        
        if ([host isEqual: _allowURLHost]) {
            // 允许跳转
            decisionHandler(WKNavigationActionPolicyAllow);
            return;
        }
        // 不允许跳转
        decisionHandler(WKNavigationActionPolicyCancel);
    }
}

- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)())completionHandler {
    
    [[[UIAlertView alloc] initWithTitle:@"温馨提示" message:message delegate:nil cancelButtonTitle:@"确认" otherButtonTitles: nil] show];
    
    completionHandler();
}

- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler {
    
    NSLog(@"message = %@", message);
    
}

- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString *))completionHandler {
    
    NSLog(@"prompt = %@ || %@", prompt, defaultText);
}

// 从web界面中接收到一个脚本时调用
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    
    NSLog(@"%@", message);
}

@end